var EN = {empty:"no data",lastpage:"Last page",firstpage:"First page",error:"system busy!",first:"<<",end:">>",back:"<",next:">",page:"pages",record:"record",total:"total"};
var CN = {empty:"没有数据",lastpage:"已经在末页",firstpage:"已经在首页",error:"系统繁忙!",first:"<<",end:">>",back:"<",next:">",page:"页",record:"条记录",total:"共"};
var tablist = {};
$(function() {
	mpage 	= (function() {
		var website		= null, 
		isDebug 		= false,
		pagename 		= '',
		module 			= "",
		searchkey 		= "",//查询内容
		jumpkey 		= null,//跳转页
		condition 		= "",//conditions part1:.cdititle part2:#cdtion part3:.cdit
		requestext 		= "",//request ext 20130502
		columnhide      = false,
		init			= function() {
			website 	= site.web;//页面必须赋值			
			pagename 	= site.page;
			module 		= site.module;
			if(site.columnh)
			columnhide  = site.columnh;
			$(".jumprow").click(function(){//跳转按钮
				mpage.gotopage(this);
		    });
			$("#go").click(function(){//查询按钮
				mpage.search();
			});
			
			$(".orderkey").click(function(){//排序按钮
		        $(".orderkey").css("font-weight","normal");
		        
		        if($(this).attr("flag")==0){
		            $(this).attr("flag","1");
		            $(this).css("font-weight","bold");
		            var c = mpage.getkey();
		            mpage.getList("init",c.condition,tablist.current,"",$(this).attr("key"));
		        }else{
		            $(this).attr("flag","0");
		            var c = mpage.getkey();
		            mpage.getList("init",c.condition,tablist.current);
		        }
		    });

			$(".table_checkbox_select").click(function(){//全选按钮       
				$(".table_checkbox").attr("checked", true);
		        if($(this).attr("checked")==null)
		        	$(".table_checkbox").attr("checked", false);
			});
			if(columnhide)//设置隐藏列功能是否打开
				setcolumnh();
			getkey();
			getList("init",condition,1);
		},
		getkey = function(){//获取查询,跳转页数数值
			searchkey 		= $("#searchkey").val();
			jumpkey 		= $("#jumpkey").val();
			condition 		= $("#cdtion").val();
			if(!isDigit(jumpkey))//屏蔽非数据页面
				jumpkey = tablist.current;
			return {searchkey:searchkey,jumpkey:jumpkey,condition:condition};
		},
		getselected = function(){//获取已选数据
			var selectIds = [] , id = null ;
			   $(".table_checkbox").each(function() {
				   if($(this).attr("checked")){
		           id = $(this).val();
		           name = $(this).attr("name");
		           selectIds.push(id);
				   }
		       });
			return selectIds;
		},
		getName = function(id,name){//获取已选名称//TODO
			var value = null;
			$(":checkbox").each(function() {		     
				if($(this).val()==id){	
					value = $(this).attr(name);
					return;
				}
		    });
			return value;
		},
		cancelSelected = function(){//取消全选
			$(".table_checkbox").each(function(){
				$(this).attr("checked",false);
		    });
			$(".table_checkbox_select").attr("checked",false);
		},
		btnaction = function(button){//分页按钮
			getkey();
			var act = $(button).attr("act"),
				btnkey = $(button).attr("key");
			switch(act){
			   case "next":
				   if(tablist.dataC==null||tablist.status=="end"){//判断是否last
					   tablemsg(msg.lastpage);
		               return;
		           } 
				   if(tablist.position=="B"){
					   mpage.modalfactory(tablist.dataC,"C");
					   var c = mpage.getkey();
		               getList(act,c.condition,btnkey,searchkey,tablist.order);
				   }
				 break;
			   case "back":
				   if(tablist.dataA==null||tablist.status=="first"){//判断是否第一页
					   tablemsg(msg.firstpage);
		               return;
		           } 
				   if(tablist.position=="B"){
					   mpage.modalfactory(tablist.dataA,"A");
					   var c = mpage.getkey();
		               getList(act,c.condition,btnkey,searchkey,tablist.order);//重新载入数据  
				   }
		         break;
			   case "jump":
			   case "end":
			   case "first":
				   if(act=="end"&&tablist.status=="end"){//判断是否last
					   tablemsg(msg.lastpage);
		               return;
		           } 
				   if(act=="first"&&tablist.status=="first"){//判断是否第一页
					   tablemsg(msg.firstpage);
		               return;
		           } 
				   getkey();
				   getList(act,condition,jumpkey,searchkey,tablist.order);
				   break;
			}
		},
		setstep = function(act){//生成分页按钮
			var pagelable = '<span class="right">['+tablist.current+'-'+tablist.pages+msg.page+']&nbsp;&nbsp;['+msg.total+tablist.records+msg.record+']</span>';
			if(tablist.status=="less"){
		        $(".tabstep").empty();
		        $(".tabstep").append(pagelable);
		        return;
		    }
			$(".tabstep").empty();
			var back = '<input type="button" value="'+msg.back+'" act="back" key="'+tablist.back+'" class="pagebtn btn" onclick="mpage.btnaction(this)"/>';
		    var next = '<input type="button" value="'+msg.next+'" act="next" key="'+tablist.next+'" class="pagebtn btn" onclick="mpage.btnaction(this)"/>';
		    
		    switch (parseInt(tablist.template)) {//根据模式生成分页按钮
		    case 1:
		    	$(".tabstep").append(back+next+pagelable);
		    	break;
			case 2:
			    var first = '<input type="button" value="'+msg.first+'" act="first" key="1" class="pagebtn  btn" onclick="mpage.btnaction(this)"/>';
			    var end = '<input type="button" value="'+msg.end+'" act="end" key="'+tablist.pages+'" class="pagebtn  btn" onclick="mpage.btnaction(this)"/>';
			    var jump = '<input type="text" value="1" id="jumpkey" class="span1" style="margin:5px;"/><input type="button" value="Go" act="jump" key="'+tablist.current+'" class="pagebtn btn" onclick="mpage.btnaction(this)"/>';
			    $(".tabstep").append(first+back+jump+next+end+pagelable);
				break;
			}
		},
		modalfactory = function(data,position){//生成列表内容 //TODO 需要变化的地方
			$(".tablist").empty();
			tablist.position = position;//设置数据所在位置
			var tdValue =  "",
			    rowclass = "",
		        td = function(arg){
		        return "<td>"+arg+"</td>";
			};
			
			for ( var element in data) {
			    var checkbox = '<input type="checkbox" data-id="'+data[element].fid+'" data-name="'+data[element].file_name+'" name="choice[]" class="table_checkbox" />',
				tdValue =td(checkbox)+ 
				   td(data[element].fid)+ 
				   td(data[element].file_name)+ 
				   td(data[element].file_type)+ 
				   td(data[element].addtime)+ 
		           td(data[element].position);
  				   rowclass = element%2;//行样式
				   $(".tablist").append("<tr class='tr"+rowclass+"'>"+tdValue+"</tr>");
			}
		},
		tablemsg = function(value,obj){//消息显示
			var msgDIV=$(".datatablemsg");
			msgDIV.html(value);
			msgDIV.height("0px").show();
			if(value.length>=10){
				msgDIV.width("130px");
			}
			msgDIV.animate( { height: "35px" }, { queue: false, duration: 1000 }).delay(1300).fadeOut();
		},
		search = function() {//查询按钮:缺省按钮
			getkey();
			getList("init",condition,1,searchkey);
		},
		gotopage = function(arg) {//跳转按钮:缺省按钮 
			getkey();
			getList("jump",condition,tablist.current,searchkey,"",$(arg).attr("key"));
		},		
		getList = function(act,condition,page,wvar,ovar,rows){//方法,页面,where,order
			 var web = website+module+"/"+pagename+requestext;
			 if(!pagename){
				 web=  website+module+requestext;
			 }
			 var json = {web:web,
		    		   act:act,
		    		   page:page,
		    		   wvar:wvar,
		    		   ovar:ovar,
		    		   cdit:condition,
		    		   rows:rows
		    		   };
			 	if(isDebug)
                 alert("web:"+json.web+"\n\nact:"+json.act+"\n\nsearch:"+wvar+"\n\ncondition:"+json.cdit);
		       $.ajax({  cache: false
		                , type: "GET"
		                ,  url: json.web
		                , dataType: "json"
		                , data: json       
		                , error: function (XMLHttpRequest, textStatus, errorThrown) {
		                	tablemsg(msg.error);
		                	if(isDebug)
		                        alert(textStatus+":"+XMLHttpRequest.status);
		                }
		                , success: function (data) {
		                    complete(data,json);
		                  }     
		       });
		},
		complete = function(data,json){
			if(!data||data.records==0){
				$(".tablist").empty();
				tablemsg(msg.empty);
				return;
			}
			if(data.code==0){
				tablemsg(msg.error);
				return;
			}
				
			switch(json.act){
			  case "init"://初始化数据
			  case "jump"://跳转
			  case "first"://首页
			  case "end"://末页
			  case "next"://前进
			  case "back"://后退
				    tablist = data;
				    if(json.act=="next" || json.act=="back"){
				    	tablist.position = "B";//后台加载数据,等待用户再次点击后导入
				    }else{
				    	mpage.modalfactory(tablist.dataB,"B");//直接导入数据
				    }
				    setstep(json.act);
				    $("#searchkey").val(tablist.search);
				    $("#jumpkey").val(tablist.current);
				    break;
			}
    		cancelSelected();
    		if(site.callback){//页面必须对site.call赋值 TODO:做异常处理
    			callback(site.call);
    		}
		},
		setcolumnh = function(){
			//设置隐藏列功能:
			//前提条件:1:datatable,trcolumn,tablist 
			//2:隐藏列按钮dropdown-toggle,columnh
			var columns;//列数
			$(".columnh").empty();
			$(".trcolumn>td:not(:first)").each(function(index){
		        $(".columnh").append("<li class='active' onclick='g("+(index+1)+");'><a href='#' style='overflow:hidden'><span style='display:block;float:left'>"+$(this).html()+"</span><i class='icon-ok' style='float:right'></i></a></li>");
		    });
		    columns = $(".columnh>li").length +1;
		    $(".columnh").append('<li class="divider"></li>');
		    $(".columnh").append("<li onclick='g("+(columns+1)+");'><a href='#'>全部显示</a></li>");
		    
		    g = function(n){
		        if(n == columns+1){//显示全部
		            $(".tablist>tr>td").show();
		            $(".trcolumn>td").show();
		            $(".columnh>li").attr("class","");//显示样式设置
		            $(".columnh>li>a>i").attr("class","");
		            $(".columnh>li").attr("class","active");
		            $(".columnh>li>a>i").attr("class","icon-ok");
		            $(".columnh>li:eq("+(n-1)+")").attr("class","");
		            return;
		        }
		        $(".trcolumn>td:eq("+n+")").toggle();
		        $(".tablist>tr").each(function(){
		         $(this).find("td:eq("+n+")").toggle();
		        });
		        if("none" == $(".trcolumn>td:eq("+n+")").css("display")){
		            $(".columnh>li:eq("+(n-1)+")").attr("class","");
		            $(".columnh>li:eq("+(n-1)+")>a>i").attr("class","");
		        }else{
		            $(".columnh>li:eq("+(n-1)+")").attr("class","active");
		            $(".columnh>li:eq("+(n-1)+")>a>i").attr("class","icon-ok");
		        }
		    };
		},
		setext = function(value){
			if(value)requestext = value;
		},
		callback = function(func){//回调函数
			func();
		};
		
		return { 
			init 			: init,
			getkey 			: getkey,
			getselected 	: getselected,
			getName 		: getName,
			cancelSelected 	: cancelSelected,
			search 			: search,
			modalfactory 	: modalfactory,
			tablemsg 		: tablemsg,
			btnaction 		: btnaction,
			gotopage 		: gotopage,
			setext 			: setext,
			callback 		: callback,
			getList 		: getList
		};
	})();	
});

function isDigit(s) 
{ 
var patrn=/^[0-9]+$/; 
if (!patrn.exec(s)) return false; 
return true ;
}